# 使用flask框架随机生成一些接口
# 数据放在web.db中

from flask import Flask, request, jsonify
import random
import sqlite3
from flask_docs import ApiDoc


app = Flask(__name__)

app.config["API_DOC_METHODS_LIST"] = ["GET", "POST"]

ApiDoc(
    app,
    title="tengtengのAPI",
    version="1.0.0",
    description="A tengtengのAPI",
)

@app.route('/random', methods=['GET'])
def random_number():
    # 获取url中的参数min, max
    min_num = request.args.get('min', default=1, type=int)
    max_num = request.args.get('max', default=100, type=int)
    
    num = random.randint(min_num, max_num)
    return jsonify({'random_number': num})


@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    # connect to database
    with sqlite3.connect('./web/web.db') as conn:
        c = conn.cursor()
        # check if user exists
        c.execute("SELECT name, password FROM user WHERE name=?", (username,))
        user = c.fetchone()
        if user is None:
            return jsonify({'message': 'User not found'}), 200
        # check if password is correct
        if password == user[1]:
            return jsonify({'message': 'Login successful'}), 200
        else:
            return jsonify({'message': 'Incorrect password'}), 200





if __name__ == '__main__':
    
    app.run(debug=True)